function numberWithCommas(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}

function showProducts(){
     $('.addItem').delegate('','click', function() {
         addItem(this);
    });
     $('.parentShowDelete:visible input[id^=invoice_price_]').delegate('','input', function() {
            calculateAmount()
    });
     $('.parentShowDelete:visible input[id^=invoice_qty_]').delegate('','input', function() {
            calculateAmount()
    });
     $('input[id^=invoice_discount]').delegate('','input', function() {
            calculateAmount()
    });
     $('select[id^=invoice_discount]').delegate('','change', function() {
            calculateAmount()
    });
}

function addItem(caller){
    $('.parentShowDelete:first').parent().append($('.hiddenItems').html()); 
    $('.parentShowDelete:visible  select:not(.chzn-select)').addClass('chzn-select');
    updateItemGrid();
    displayDeleteLinks();
    showProducts();
    $(".chzn-select").chosen();
    caller.event.stopPropagation();
}

function deleteItem(caller){
    $(caller).parent().parent().remove();
    updateItemGrid();
    displayDeleteLinks();
    calculateAmount();
}

function updateItemGrid(){
    var index1 = 1;
    $('.parentShowDelete:visible select[id^=invoice_product_id_]').each(function(){ 
            $(this).attr('id','invoice_product_id_'+index1);
            $(this).attr('name','invoice[product_id_'+index1+']');
            index1++;
    });
    var index2 = 1;
    $('.parentShowDelete:visible select[id^=invoice_unit_id_]').each(function(){ 
            $(this).attr('id','invoice_unit_id_'+index2);
            $(this).attr('name','invoice[unit_id_'+index2+']');
            index2++;
    });
    var index3 = 1;
    $('.parentShowDelete:visible input[id^=invoice_price_]').each(function(){ 
            $(this).attr('id','invoice_price_'+index3);
            $(this).attr('name','invoice[price_'+index3+']');
            index3++;
    });
    var index4 = 1;
    $('.parentShowDelete:visible input[id^=invoice_qty_]').each(function(){ 
            $(this).attr('id','invoice_qty_'+index4);
            $(this).attr('name','invoice[qty_'+index4+']');
            index4++;
    });
  
}


function displayDeleteLinks(){
    if($('.parentShowDelete:visible').length > 1){
        if(!($('.parentShowDelete:visible .formRight:first .showDeleteIcon').length)){
            $('.parentShowDelete:visible .formRight:first').append('<div class="showDeleteIcon" onClick="deleteItem(this)"></div>');
        }
    }else{
        $('.parentShowDelete:visible .formRight:first .showDeleteIcon').remove();
    }
}


function calculateAmount(){
    var totalPrice = 0;
    var floatRegex = /^[0-9]*[.]*[0-9]*$/;
    var intRegex = /^[0-9]+$/;
    $('.parentShowDelete:visible input[id^=invoice_price_]').each(function(){
        if($(this).val() != "") {
            var price = $(this).val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            var qty = $(this).parent().next().children('input').val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
            if(floatRegex.test(price) && intRegex.test(qty)) {
                totalPrice += (parseFloat(price) * parseFloat(qty));
            }
        } 
    });
    if($('#invoice_discount_type').val() == 'percentage' && $('#invoice_discount').val() && floatRegex.test($('#invoice_discount').val()))
        totalPrice = totalPrice - ((parseFloat($('#invoice_discount').val())/100)*totalPrice)
    if($('#invoice_discount_type').val() == 'cash' && $('#invoice_discount').val() && floatRegex.test($('#invoice_discount').val()))
        totalPrice = totalPrice - parseFloat($('#invoice_discount').val())
    $('.invoiceAmount').html(numberWithCommas(totalPrice.toFixed(2)) + ' L.E');
}



function addInvoice(type,showSucessBar){
      var url = $("#url4AddInvoice").val();
      if(!type){
        $.ajax ({
            type: "GET",
            url: url,
            success: function (html)
            {
                $('#DAH').html(html);
                $(".chzn-select").chosen();
                $(".datepicker").datepicker({ dateFormat: 'yy-mm-dd' });
                showProducts();
                calculateAmount();
                if(showSucessBar)
                    $('#DAH').prepend('<div class="nNote nSuccess hideit"><p><strong>SUCCESS: </strong> Invoice added successfully. </p></div>');     
            }
        });
      }else{
          var data = $("#form").serialize() + "&count=" +  $('.parentShowDelete:visible').length
        $.ajax ({
            type: "POST",
            url: url,
            data :data,
            success: function (html)
            {
                if(html == "Done"){
                    addInvoice(false, true);
                    $('html, body').animate({scrollTop:$('#rightSide').position().top}, 'slow');
                }
                else{
                    $('#DAH').html(html);
                    $(".chzn-select").chosen();
                    $(".datepicker").datepicker({ dateFormat: 'yy-mm-dd' });
                    showProducts();
                    calculateAmount();
                }
            }
        });
      }
}



function editInvoice(type,showSucessBar,id){
      var url = $("#url4EditInvoice").val();
      if(!type){
        $.ajax ({
            type: "GET",
            url: url,
            data: "id=" + id,
            success: function (html)
            {
                $('#DAH').html(html);
                $(".chzn-select").chosen();
                $(".datepicker").datepicker({ dateFormat: 'yy-mm-dd' });
                showProducts();
                calculateAmount();
                if(showSucessBar)
                    $('#DAH').prepend('<div class="nNote nSuccess hideit"><p><strong>SUCCESS: </strong> Invoice Edited successfully. </p></div>');     
            }
        });
      }else{
          var data = $("#form").serialize() + "&count=" +  $('.parentShowDelete:visible').length + "&id=" + id
        $.ajax ({
            type: "POST",
            url: url,
            data :data,
            success: function (html)
            {
                if(html == "Done"){
                    addInvoice(false, true);
                    $('html, body').animate({scrollTop:$('#rightSide').position().top}, 'slow');
                }
                else{
                    $('#DAH').html(html);
                    $(".chzn-select").chosen();
                    $(".datepicker").datepicker({ dateFormat: 'yy-mm-dd' });
                    showProducts();
                    calculateAmount();
                }
            }
        });
      }
}



